<template>
  <div class="application-container">
    <!-- 搜索 -->
    <div class="formSearch">
      <el-form :inline="true" :model="searchData">
        <el-form-item label="用户名称">
          <el-input v-model="searchData.buyerName" maxlength="20" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchData.phone" maxlength="11" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="提现状态">
          <el-select v-model="searchData.state" clearable placeholder="请选择">
            <el-option label="待审核" :value="0" />
            <el-option label="通过" :value="1" />
            <el-option label="拒绝" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker
            v-model="searchData.dates"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <el-table
        v-loading="loading.table"
        :data="tableData"
        border
        :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
        tooltip-effect="dark"
        :style="{ width: '100%' }"
        class="dataTable"
      >
        <el-table-column prop="buyerName" label="用户名称" show-overflow-tooltip />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="withdrawalMoney" label="提现金额(元)" />
        <el-table-column label="提现方式">
          <template #default="scope">
            <span v-if="scope.row.withdrawalType === 1">微信</span>
            <span v-else-if="scope.row.withdrawalType === 2">支付宝</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="处理状态">
          <template #default="scope">
            <el-tag v-if="scope.row.state === 0" type="info">待审核</el-tag>
            <el-tag v-else-if="scope.row.state === 1" type="success">通过</el-tag>
            <el-tag v-else-if="scope.row.state === 2" type="danger">拒绝</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="申请时间" />
        <el-table-column label="操作">
          <template #default="scope">
            <div class="btnList">
              <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
              <el-button
                v-if="scope.row.state === 0"
                link
                type="primary"
                @click="handleProcess(scope.row)"
                >处理</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="searchData.page"
        v-model:page-size="searchData.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 查看/处理对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'view' ? '查看' : '处理'"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户名称">{{ detailData.buyerName }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ detailData.phone }}</el-descriptions-item>
        <el-descriptions-item label="提现方式">
          <span v-if="detailData.withdrawalType === 1">微信</span>
          <span v-else-if="detailData.withdrawalType === 2">支付宝</span>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="提现账户">{{
          detailData.withdrawalAccount
        }}</el-descriptions-item>
        <el-descriptions-item label="账户姓名">{{
          detailData.withdrawalName
        }}</el-descriptions-item>
        <el-descriptions-item label="提现金额">{{
          detailData.withdrawalMoney
        }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ detailData.createTime }}</el-descriptions-item>
        <el-descriptions-item v-if="detailData.updateTime" label="处理时间">{{
          detailData.updateTime
        }}</el-descriptions-item>
        <el-descriptions-item
          v-if="detailData.reason && detailData.state === 2"
          label="拒绝原因"
          :span="2"
        >
          {{ detailData.reason }}
        </el-descriptions-item>
      </el-descriptions>

      <div v-if="dialogType === 'process'" class="process-tip">
        * 请确认您已转账成功，再点击确认
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button v-if="dialogType === 'process'" type="primary" @click="handleConfirm"
            >确认打款</el-button
          >
          <el-button v-if="dialogType === 'process'" type="danger" @click="showRejectDialog"
            >拒绝打款</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 拒绝原因对话框 -->
    <el-dialog v-model="rejectDialogVisible" title="拒绝打款" width="500px">
      <el-form ref="rejectFormRef" :model="rejectForm" :rules="rejectRules">
        <el-form-item label="拒绝原因" prop="reason">
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            maxlength="200"
            :rows="4"
            placeholder="请输入拒绝原因"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取 消</el-button>
          <el-button type="danger" @click="handleReject">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { FinanceService } from '@/api/financeApi'
  import { ApiStatus } from '@/utils/http/status'
  import type {
    BuyerWithdrawalType,
    BuyerWithdrawalGetAllParam,
    BuyerWithdrawalGetByIdParam
  } from '@/api/model/financeModel'

  // 表格相关
  const loading = ref({
    table: false
  })
  const tableData = ref<BuyerWithdrawalType[]>([])
  const total = ref(0)

  // 搜索表单
  const searchData = reactive<BuyerWithdrawalGetAllParam & { phone?: string }>({
    page: 1,
    pageSize: 10,
    buyerName: '',
    phone: '',
    state: undefined,
    dates: []
  })

  // 对话框相关
  const dialogVisible = ref(false)
  const rejectDialogVisible = ref(false)
  const dialogType = ref<'view' | 'process'>('view')
  const detailData = ref<BuyerWithdrawalType>({})

  // 拒绝表单
  const rejectFormRef = ref()
  const rejectForm = reactive({
    reason: ''
  })
  const rejectRules = {
    reason: [{ required: true, message: '请输入拒绝原因', trigger: 'blur' }]
  }

  // 获取用户提现申请列表
  const getAll = async () => {
    loading.value.table = true
    try {
      const res = await FinanceService.buyerWithdrawalGetAll(searchData)
      if (res.code === ApiStatus.success) {
        tableData.value = res.data.list
        total.value = res.data.total
      } else {
        ElMessage.error(res.message || '获取用户提现申请列表失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('获取用户提现申请列表失败')
    } finally {
      loading.value.table = false
    }
  }

  // 处理查询
  const search = () => {
    searchData.page = 1
    getAll()
  }

  // 重置搜索条件
  const reset = () => {
    searchData.buyerName = ''
    searchData.phone = ''
    searchData.state = undefined
    searchData.dates = []
    searchData.page = 1
    getAll()
  }

  // 处理分页
  const handleSizeChange = (val: number) => {
    searchData.pageSize = val
    getAll()
  }

  const handleCurrentChange = (val: number) => {
    searchData.page = val
    getAll()
  }

  // 查看详情
  const handleView = async (row: BuyerWithdrawalType) => {
    try {
      const res = await FinanceService.buyerWithdrawalGetById({
        withdrawalId: row.withdrawalId!
      } as BuyerWithdrawalGetByIdParam)
      if (res.code === ApiStatus.success) {
        detailData.value = res.data
        dialogType.value = 'view'
        dialogVisible.value = true
      } else {
        ElMessage.error(res.message || '获取详情失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('获取详情失败')
    }
  }

  // 处理提现申请
  const handleProcess = async (row: BuyerWithdrawalType) => {
    try {
      const res = await FinanceService.buyerWithdrawalGetById({
        withdrawalId: row.withdrawalId!
      } as BuyerWithdrawalGetByIdParam)
      if (res.code === ApiStatus.success) {
        detailData.value = res.data
        dialogType.value = 'process'
        dialogVisible.value = true
      } else {
        ElMessage.error(res.message || '获取详情失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('获取详情失败')
    }
  }

  // 确认打款
  const handleConfirm = () => {
    ElMessageBox.confirm('确认已转账成功并完成打款吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        try {
          const params: BuyerWithdrawalGetByIdParam = {
            withdrawalId: detailData.value.withdrawalId!,
            state: 1 // 同意
          }
          const res = await FinanceService.buyerWithdrawalHandle(params)
          if (res.code === ApiStatus.success) {
            ElMessage.success('处理成功')
            dialogVisible.value = false
            getAll()
          } else {
            ElMessage.error(res.message || '处理失败')
          }
        } catch (error) {
          console.error(error)
          ElMessage.error('处理失败')
        }
      })
      .catch(() => {
        // 取消操作
      })
  }

  // 显示拒绝对话框
  const showRejectDialog = () => {
    rejectForm.reason = ''
    dialogVisible.value = false
    rejectDialogVisible.value = true
  }

  // 拒绝打款
  const handleReject = () => {
    rejectFormRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          const params: BuyerWithdrawalGetByIdParam = {
            withdrawalId: detailData.value.withdrawalId!,
            state: 2 // 拒绝
          }
          const res = await FinanceService.buyerWithdrawalHandle(params)
          if (res.code === ApiStatus.success) {
            ElMessage.success('处理成功')
            rejectDialogVisible.value = false
            getAll()
          } else {
            ElMessage.error(res.message || '处理失败')
          }
        } catch (error) {
          console.error(error)
          ElMessage.error('处理失败')
        }
      }
    })
  }

  // 初始化
  onMounted(() => {
    getAll()
  })
</script>

<style lang="scss" scoped>
  .application-container {
    padding: 20px;
    background-color: #fff;

    .formSearch {
      margin-bottom: 20px;
      padding: 20px;
      background-color: #f5f7fa;
      border-radius: 4px;
    }

    .table-container {
      margin-bottom: 20px;
      overflow-x: auto;
      overflow-y: auto;
      touch-action: pan-y;
      -webkit-overflow-scrolling: touch;
    }

    .dataTable {
      margin-bottom: 0;
      width: 100%;
    }

    .pagination-wrapper {
      display: flex;
      overflow-x: auto;
      overflow-y: hidden;
      touch-action: pan-x;
      -webkit-overflow-scrolling: touch;
      padding: 10px 0;
      justify-content: flex-start;

      ::v-deep .el-pagination {
        display: flex;
        justify-content: flex-start;
        min-width: auto !important;
        margin: 0 !important;
        padding: 0 10px !important;
      }

      ::v-deep .el-pagination__sizes {
        margin-right: 10px;
      }

      ::v-deep .el-pagination__total {
        margin-right: 10px;
      }

      ::v-deep .el-pagination__jump {
        margin-left: 10px;
      }
    }

    .btnList {
      display: flex;
      gap: 10px;
    }

    .process-tip {
      margin-top: 15px;
      padding: 10px;
      background-color: #fffbe6;
      border: 1px solid #ffe58f;
      border-radius: 4px;
      color: #faad14;
      font-size: 14px;
    }

    .dialog-footer {
      text-align: right;
    }
  }

  @media screen and (max-width: $device-phone) {
    .application-container {
      padding: 10px;

      .formSearch {
        padding: 15px;

        :deep(.el-form-item) {
          margin-bottom: 15px;
        }
      }
    }
  }
</style>
